#!/usr/bin/python
#-*- coding:utf-8 -*-

from os import path
from data import Site
from data import City
from data import Kingdom
import xml.dom.minidom as minidom
import tagmap_globals as tg

def load_atlas(filename='atlas.xml'):
	doc = minidom.parse(filename)
	
	sites = {}

	mapfile = doc.childNodes[0].getAttribute('imagem')
	scale = float(doc.childNodes[0].getAttribute('escala'))

	center_node = doc.childNodes[0].getElementsByTagName('marcozero')[0]
	center = (int(center_node.getAttribute('x')),
					int(center_node.getAttribute('y')))

	for site_node in doc.childNodes[0].childNodes[2:]:
		if site_node.nodeType == site_node.ELEMENT_NODE:
			site = process_site(site_node)
			sites[site.name] = site

	return (mapfile, center, scale, sites)

def process_site(node):
	if node.nodeName == 'reino':
		site = Kingdom(node.getAttribute('nome').encode('utf-8'))
		cities_nodes = node.getElementsByTagName('cidades')
		if cities_nodes:
			for city in cities_nodes[0].childNodes:
				if city.nodeType == city.ELEMENT_NODE:
					site.cities.append(process_site(city))
	elif node.nodeName == 'cidade':
		capital = node.getAttribute('tipo')
		site = City(node.getAttribute('nome').encode('utf-8'), capital=='capital')
	else:
		if node.nodeName == 'regiao':
			type = Site.REGION
		elif node.nodeName == 'floresta':
			type = Site.FOREST
		elif node.nodeName == 'montanha':
			type = Site.MOUNTAIN
		elif node.nodeName == 'agua':
			type = Site.WATER
		elif node.nodeName == 'ilha':
			type = Site.ISLAND
		else:
			type = Site.PLACE
		site = Site(node.getAttribute('nome').encode('utf-8'), type)

	image = node.getAttribute('imagem')
	if image:
		site.image = image

	quote = node.getElementsByTagName('citacao')
	if quote:
		quote = quote[0]
		site.quote = (quote.childNodes[0].nodeValue.encode('utf-8').strip(),
								quote.getAttribute('autor').encode('utf-8'))

	node_descr = node.getElementsByTagName('descricao')
	if node_descr:
		site.description = node_descr[0].\
									childNodes[0].nodeValue.encode('utf-8').strip()

	site.areaType, site.area = \
							process_area(node.getElementsByTagName('area')[-1])

	return site							

def process_place(site):
	if site.nodeName == 'cidade':
		region = City(site.getAttribute('nome').encode('utf-8'))
		capital = site.getAttribute('tipo')
		region.capital = (capital == 'capital')
	else:
		region = Site(site.getAttribute('nome').encode('utf-8'))

def process_area(node):
	if node:
		tipo = node.getAttribute('tipo')
		if tipo == 'circulo':
			areaType = Site.CIRCLE
			coord = node.getElementsByTagName('coordenadas')[0]
			coords = (int(coord.getAttribute('x')),
							int(coord.getAttribute('y')),
							int(coord.getAttribute('raio')))
		elif tipo == 'ponto':
			areaType = Site.CIRCLE
			coord = node.getElementsByTagName('coordenadas')[0]
			coords = (int(coord.getAttribute('x')), int(coord.getAttribute('y')), 4)
		else:
			areaType = Site.POLYGON
			coords = []
			for coord in node.getElementsByTagName('coordenadas'):
				coords.append((int(coord.getAttribute('x')),
									int(coord.getAttribute('y'))))
			coords.append(coords[0])
			coords = tuple(coords)

	return (areaType, coords)


def load_marks(filename):
	doc = minidom.parse(filename)

	marks = []
	for mark_node in doc.childNodes[0].childNodes:
		if mark_node.nodeType == mark_node.ELEMENT_NODE and \
			mark_node.nodeName == 'marco':
			marks.append((mark_node.getAttribute('nome'),
							(int(mark_node.getAttribute('x')),
							int(mark_node.getAttribute('y')))))
	
	return marks


def save_marks(marks, filename):
	doc = minidom.Document()

	root_node = doc.createElement('trilha')
	for mark in marks:
		mark_node = doc.createElement('marco')

		if mark[0]:
			mark_node.setAttribute('nome', mark[0])
		mark_node.setAttribute('x', str(mark[1][0]))
		mark_node.setAttribute('y', str(mark[1][1]))

		root_node.appendChild(mark_node)

	doc.appendChild(root_node)
	
	f = open(filename, 'w')
	f.write(doc.toprettyxml(encoding='utf-8'))
	f.close()
	
def export_marks_as_html(marks, filename):
	f = open(path.join(tg.data_dir, 'template.html'), 'r')
	page = f.read()
	f.close()
	
	places = ''
	for mark in marks:
		places += \
				'<tr>\n\t<td>%dkm</td>\n\t<td>%s</td>\n\t<td>%s</td>\n</tr>\n' % \
				mark
	
	f = open(filename, 'w')
	f.write(page.replace('_LOCAIS', places))
	f.close()

if __name__ == '__main__':
	sites = load_atlas(path.join(tg.data_dir, 'atlas.xml'))
	
	print sites

	'''	
	for name in sites.keys():
		site = sites[name]

		print site.name
		print site.image
		print site.description
		if type(site) == type(Kingdom):
			print site.quote
			print site.cities
		print site.areaType
		print site.area
		print '\n'
		
	print sites.keys()
	'''
